dojo.provide("uws.drawing.ComponentManager");

dojo.declare('uws.drawing.ComponentManager',null,{
	/*
		Adds, edits, gets, and deletes components from the data store. It is managed per diagram.
	*/
	idcounter:null,
	components:null,
	
	constructor:function(start){
		this.idcounter = start;
		this.components = [];
	},
	newItem:function(umltype, x, y, sortOrder, label, description, diagram, custom){
		dataStore.newItem(
			{
				id: "component_"+(componentManager.idcounter),
				name: "component_"+(componentManager.idcounter),
				uwstype: 'component',
				umltype: umltype,
				x: x,
				y: y,
				comp_children: [],
				sortOrder: sortOrder,
				label: label,
				description: description,
				custom: custom
			},
			{
				parent: diagram,
				attribute: 'children'
			}
		);
		
		dataStore.setValue(root,"comp_counter",componentManager.idcounter+1);
		return "component_"+(this.idcounter++);
	},
	addItem:function(id,component){
		this.components[id] = component;
	},
	getById:function(id){
		return this.components[id];
	},
	removeItem:function(id, removeConnections){
		if(this.components[id]==null) return;
		if(removeConnections){
			dataStore.fetch({
				query: {ref1_id: id},
				queryOptions: {deep:true, ignoreCase:false},
				onItem : function(item, request) {
					connectionManager.removeItem(dataStore.getValue(item, "id"));
				}
			});
			dataStore.fetch({
				query: {ref2_id: id},
				queryOptions: {deep:true, ignoreCase:false},
				onItem : function(item, request) {
					connectionManager.removeItem(dataStore.getValue(item, "id"));
				}
			});
		}
		
		if(id==propertiesManager.currentItem){
			dojo.byId("propertiesName").innerHTML = '';
			dojo.byId("propertiesDiv").innerHTML = '<span style="font-style:italic">Please select an item.</span>';
			propertiesManager.currentItem = null;
		}
		
		console.debug("Remove: "+id);
		this.components[id].destroy();
		delete(this.components[id]);
	},
	destroyItem:function(id){
		//destroy connections first
		dataStore.fetch({
			query: {ref1_id: id},
			queryOptions: {deep:true, ignoreCase:false},
			onItem : function(item, request) {
				connectionManager.destroyItem(dataStore.getValue(item, "id"));
			}
		});
		
		dataStore.fetch({
			query: {ref2_id: id},
			queryOptions: {deep:true, ignoreCase:false},
			onItem : function(item, request) {
				console.debug(dataStore.getValue(item, "id"));
				connectionManager.destroyItem(dataStore.getValue(item, "id"));
			}
		});
		
		this.removeItem(id, false);			//do not remove connections. It is already destroyed
		console.debug("Destroy: "+id);
		dataStore.fetchItemByIdentity({
			identity: id,
			onItem: function(item){
				dataStore.deleteItem(item);
			}
		});
	}
});